//
//  SWChildAddViewController.swift
//  ChildStory
//
//  Created by linhan on 16/9/5.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWChildAddViewController: SWBaseViewController,SWAPIComponent
{
    //强制完成创建任务（不能返回）
    var forceSupplement:Bool = false
    
    private var _gender:Int = SWGender.Unknow.rawValue
    private var _role:Int = SWRole.Mother.responseValue
    
    lazy private var _toolBar:UIToolbar = UIToolbar()
    lazy private var _datePicker:UIDatePicker = UIDatePicker()
    private var _dateTextField:UITextField = UITextField()
    private var _nameTextField:UITextField = UITextField()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewDidAppear(_ animated: Bool)
    {
        super.viewDidAppear(animated)
        if appearedFirstTime
        {
            appearedFirstTime = false
            if forceSupplement
            {
                //当到资料补全页来，说明已经注册成功，之前的注册登录页面已经不再需要了
                navigationController?.viewControllers = [self]
            }
        }
    }
    
    deinit
    {
        trace("DEINIT SWChildAddViewController")
    }
    
    private func setup()
    {
        title = "宝宝信息填写"
        view.backgroundColor = UIColor.white
        
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        view.addGestureRecognizer(tapGesture)
        
        let PlaceholderColor:UIColor = UIColor(hex: "0xC2C2C2")
        let InputColor:UIColor = UIColor.white
        
        let roleView = UIView()
        roleView.frame = CGRectMake(0, 70, view.width, 50)
        view.addSubview(roleView)
        
        let roleLabel = UILabel()
        roleLabel.font = UIFont.systemFont(ofSize:14)
        roleLabel.text = "我是"
        roleLabel.textColor = UIColor.darkGray
        roleLabel.sizeToFit()
        roleLabel.frame = CGRectMake(100, 20, roleLabel.width, roleLabel.height)
        roleView.addSubview(roleLabel)
        
        let fatherBtn:UIButton = UIButton(type:.system)
        fatherBtn.backgroundColor = UIColor.lightGray
        fatherBtn.setTitle("宝爸", for: .normal)
        fatherBtn.frame = CGRectMake(roleLabel.right, 0, 40, 40)
        fatherBtn.tag = SWRole.Father.responseValue
        fatherBtn.addTarget(self, action: #selector(roleBtnTapped(_:)), for: .touchUpInside)
        roleView.addSubview(fatherBtn)
        
        let motherBtn:UIButton = UIButton(type:.system)
        motherBtn.backgroundColor = UIColor.lightGray
        motherBtn.setTitle("宝妈", for: .normal)
        motherBtn.frame = CGRectMake(fatherBtn.right + 20, 0, 40, 40)
        motherBtn.tag = SWRole.Mother.responseValue
        motherBtn.addTarget(self, action: #selector(roleBtnTapped(_:)), for: .touchUpInside)
        roleView.addSubview(motherBtn)
        
        
        
        //分割线
        let segmentationLine:UIView = UIView(frame:CGRectMake(0,roleView.bottom + 20, view.width,0.5))
        segmentationLine.backgroundColor = UIColor.darkGray
        view.addSubview(segmentationLine)
        
        //名称
        _nameTextField.frame = CGRectMake(0, segmentationLine.bottom + 20, view.width, 30)
        _nameTextField.backgroundColor = UIColor(white: 0.97, alpha: 1)
        _nameTextField.attributedPlaceholder = NSMutableAttributedString(string: "请输入宝宝名字", attributes: [NSForegroundColorAttributeName:PlaceholderColor])
        view.addSubview(_nameTextField)
        
        //性别
        let genderLabel = UILabel()
        genderLabel.text = "宝宝性别"
        genderLabel.sizeToFit()
        genderLabel.frame = CGRectMake(0, _nameTextField.bottom + 20, genderLabel.width, genderLabel.height)
        view.addSubview(genderLabel)
        
        let GenderBtnSize = CGSizeMake(40, 40)
        let genderBtnView = UIView(frame: CGRectMake(0, genderLabel.bottom, view.width, GenderBtnSize.height))
        view.addSubview(genderBtnView)
        
        let boyBtn:UIButton = UIButton(type:.system)
        boyBtn.backgroundColor = UIColor.lightGray
        boyBtn.setTitle("男", for: .normal)
        boyBtn.frame = CGRectMake(0, 0, GenderBtnSize.width, GenderBtnSize.height)
        boyBtn.tag = SWGender.Male.rawValue
        boyBtn.addTarget(self, action: #selector(genderBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(boyBtn)
        
        let girlBtn:UIButton = UIButton(type:.system)
        girlBtn.backgroundColor = UIColor.lightGray
        girlBtn.setTitle("女", for: .normal)
        girlBtn.frame = CGRectMake(0, 0, GenderBtnSize.width, GenderBtnSize.height)
        girlBtn.tag = SWGender.Female.rawValue
        girlBtn.addTarget(self, action: #selector(genderBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(girlBtn)
        
        let unknownBtn:UIButton = UIButton(type:.system)
        unknownBtn.backgroundColor = UIColor.lightGray
        unknownBtn.setTitle("未知", for: .normal)
        unknownBtn.frame = CGRectMake(0, 0, GenderBtnSize.width, GenderBtnSize.height)
        unknownBtn.tag = 3
        unknownBtn.addTarget(self, action: #selector(genderBtnTapped(_:)), for: .touchUpInside)
        genderBtnView.addSubview(unknownBtn)
        
        LayoutUtil.distributeHAverageABS([boyBtn, girlBtn, unknownBtn], containerWidth: genderBtnView.width)
        
        
        _datePicker.frame = CGRectMake(0, 0, view.width, 150)
        _datePicker.datePickerMode = .date
        
        
        //工具栏
        let completeBtn = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(completeBtnTapped))
        let cancelBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelBtnTapped))
        let spaceBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        
        _toolBar.sizeToFit()
        _toolBar.tintColor = UIColor.darkGray
        _toolBar.barTintColor = UIColor.white
        _toolBar.items = [cancelBtn, spaceBtn, completeBtn]
        
        
        //生日
        _dateTextField.frame = CGRectMake(0, genderBtnView.bottom, view.width, 30)
        _dateTextField.backgroundColor = UIColor(white: 0.97, alpha: 1)
        _dateTextField.inputAccessoryView = _toolBar
        _dateTextField.inputView = _datePicker
        view.addSubview(_dateTextField)
        
        let createBtn:UIButton = UIButton(type:.system)
        createBtn.backgroundColor = UIColor.lightGray
        createBtn.setTitle("完成", for: .normal)
        createBtn.frame = CGRectMake(30, _dateTextField.bottom + 50, view.width - 60, 50)
        createBtn.addTarget(self, action: #selector(createBtnTapped), for: .touchUpInside)
        view.addSubview(createBtn)
    }
    
    private func createChild()
    {
        /**
        let name = _nameTextField.text ?? SW.Config.DefaultKidsName
        let req = SWAddChildReq()
        req.screenName = name
        req.infantName = name
        req.gender = _gender
        req.birthday = _datePicker.date as NSDate
        req.role = _role
        req.successCallback = {[weak self] response,cache in
            SWAccountManager.sharedManager().fetchChildrenInfo(successCallback: nil, failCallback: nil)
            self?.loginSuccess()
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus: "创建失败，请重试")
        }
        load(req)
 **/
    }
    
    private func fetchChildrenInfo()
    {
        SWAccountManager.sharedManager().fetchChildrenInfo(successCallback:{[weak self] children in
            SWAccountManager.sharedManager().account?.children = children
            self?.loginSuccess()
            }, failCallback: {[weak self] error in
                self?.loginSuccess()
            })
        
    }
    
    private func loginSuccess()
    {
        SVProgressHUD.showSuccess(withStatus:"登陆成功")
        SWMainApplication.sharedApplication.rootViewController?.showMainContent()
    }
    
    @objc private func cancelBtnTapped()
    {
        _dateTextField.resignFirstResponder()
    }
    
    @objc private func completeBtnTapped()
    {
        let date:NSDate = _datePicker.date as NSDate
        _dateTextField.text = "\(date.year())年\(date.month())月\(date.day())日"
        _dateTextField.resignFirstResponder()
        //print(_datePicker.date)
    }
    
    @objc private func viewTapped()
    {
        view.endEditing(true)
    }
    
    @objc private func createBtnTapped()
    {
        Alert.show("角色", message: "角色信息填写后不能再变更，确定？", buttons: ["确定","取消"], closeHandler: {buttonIndex in
            if buttonIndex == 0
            {
                self.createChild()
            }
        })
    }
    
    @objc private func genderBtnTapped(_ button:UIButton)
    {
        _gender = button.tag
    }
    
    @objc private func roleBtnTapped(_ button:UIButton)
    {
        _role = button.tag
    }
    
}
